package com.qsxc.system.config.mybatis;

import com.baomidou.mybatisplus.core.enums.SqlMethod;
import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;

/**
 * 自定义实体更新类，不更新schoolId，否则会导致DRDS更新出错
 *
 * @author
 * 2021-04-07
 */
public class UpdateByIdNoSchoolId extends AbstractMethod {

    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        boolean logicDelete = tableInfo.isLogicDelete();
        SqlMethod sqlMethod = SqlMethod.UPDATE_BY_ID;
        String additional = this.optlockVersion() + tableInfo.getLogicDeleteSql(true, false);
        String setSQL = this.sqlSet(logicDelete, false, tableInfo, false, "et", "et.");
        String[] setsqls = setSQL.split("\n");
        StringBuilder sb = new StringBuilder();
        boolean isFirst = true;
        boolean isDbpartition = false;
        for (String item : setsqls) {
            if (item.contains("school_id")) {
                isDbpartition = true;
                continue;
            }
            if (isFirst) {
                isFirst = false;
            } else {
                sb.append("\n");
            }
            sb.append(item);
        }
        String hint = "";
        if (isDbpartition) {
            hint = "/!TDDL:" + tableInfo.getTableName() + ".school_id=#{et.schoolId}*/ \n";
        }
        String updateSql = sqlMethod.getSql();
        String sql = null;
        if (hint != "") {
            updateSql = updateSql.replace("<script>\n", "<script>\n" + hint);
            sql = String.format(updateSql, tableInfo.getTableName(), sb.toString(),
                    tableInfo.getKeyColumn(), "et." + tableInfo.getKeyProperty(), additional);
            sql = sql.replaceAll("et.id}", "et.id} <if test=\"et.schoolId != null\">and school_id=#{et.schoolId}</if>");
        } else {
            sql = String.format(updateSql, tableInfo.getTableName(), sb.toString(),
                    tableInfo.getKeyColumn(), "et." + tableInfo.getKeyProperty(), additional);
        }
        SqlSource sqlSource = this.languageDriver.createSqlSource(this.configuration, sql, modelClass);
        return this.addUpdateMappedStatement(mapperClass, modelClass, "updateByIdNoSchoolId", sqlSource);
    }
}
